package com.longyiqun.android.zhihu.Activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.Future;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

import com.longyiqun.android.zhihu.R;
import com.yalantis.phoenix.PullToRefreshView;

import org.json.JSONArray;
import org.json.JSONException;

// 主类
public class MainActivity extends BaseActivity {

    // Activity之间传值使用
    public final static String EXTRA_MESSAGE = "com.longyiqun.android.zhihu";
    // 下拉控件
    private PullToRefreshView mPullToRefreshView = null;
    public static final int REFRESH_DELAY = 2000;
    // 主页ListView的Adapter
    ArrayAdapter<JsonObject> myAdapter;

    // 页面开始渲染
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 基类方法
        super.onCreate(savedInstanceState);
        setContentView2(R.layout.activity_main);
        // 定义adapter
        myAdapter = new ArrayAdapter<JsonObject>(this, 0) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null)
                    convertView = getLayoutInflater().inflate(R.layout.mainlistview, null);
                // 取得每一个知乎Entity
                JsonObject story = getItem(position);
                // 标题
                String title = story.get("title").toString();
                // 缩略图 (150 * 150)
                JSONArray arrayImage = null;
                if (story.has("images")) {
                    try {
                        arrayImage = new JSONArray(story.get("images").toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                // 知乎Entity唯一标识ID
                String info = story.get("id").toString();
                // 填充缩略图
                ImageView imageView = (ImageView) convertView.findViewById(R.id.img);
                // 获取缩略图
                Ion.with(imageView)
                        // 定义placeholder
                        .placeholder(R.drawable.android_icon)
                        // 载入
                        .load((arrayImage != null && arrayImage.length() > 0) ? arrayImage.optString(0) : "");

                // 填充标题
                TextView titleField = (TextView) convertView.findViewById(R.id.title);
                titleField.setText(title);
                // 填充ID
                TextView infoField = (TextView) convertView.findViewById(R.id.info);
                infoField.setText(info);
                // 返回view
                return convertView;
            }
        };
        // 渲染主页list view
        ListView listView = (ListView) findViewById(R.id.mainlistview);
        // 设置list view的adapter
        listView.setAdapter(myAdapter);
        // 设置list view的点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 传递唯一标识ID
                String itemID = myAdapter.getItem(position).get("id").toString();
                // 点击事件
                ShowStoryDetail(itemID);
            }
        });
        // 获取API
        load();
        // 绑定下拉控件
        mPullToRefreshView = (PullToRefreshView) findViewById(R.id.pull_to_refresh);
        mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPullToRefreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPullToRefreshView.setRefreshing(false);
                    }
                }, REFRESH_DELAY);
            }
        });

    }

    // DEBUG用途，弹出Dialog
    protected void dialog(String itemID) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setMessage(itemID);
        builder.setTitle("Message");
        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                MainActivity.this.finish();
            }
        });
        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    // 点击list view之后，跳转到详情页面
    public void ShowStoryDetail(String id) {
        // 拼接URL
        String url = "http://news-at.zhihu.com/api/4/news/" + id;
        // 意图 -> WebViewActivity
        Intent intent = new Intent(this, WebViewActivity.class);
        // URL的传递
        intent.putExtra(EXTRA_MESSAGE, url);
        // 开启意图
        startActivity(intent);
    }

    // 定义load
    Future<JsonObject> loading;

    // load主方法
    private void load() {
        // 判断是否已经load
        if (loading != null && !loading.isDone() && !loading.isCancelled())
            return;
        // 最新消息的API
        String url = "http://news-at.zhihu.com/api/4/news/latest";
        // 开始获取API，并处理返回JSON
        loading = Ion.with(this)
                .load(url)
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        try {
                            // 获得返回JSON
                            JsonArray stories = result.getAsJsonArray("stories");
                            // 把数据填充到adapter
                            for (int i = 0; i < stories.size(); i++) {
                                myAdapter.add(stories.get(i).getAsJsonObject());
                            }
                        } catch (Exception ex) {
                            System.out.println(ex.getMessage());
                        }
                    }
                });
    }

    /*public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }*/

    /*public List<Map<String, Object>> getData() {
        final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        Ion.with(this)
                .load("http://news-at.zhihu.com/api/4/news/latest")
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        try {
                            JsonArray stories = result.getAsJsonArray("stories");
                            for (int i = 0; i < stories.size(); i++){
                                JsonObject element = stories.get(i).getAsJsonObject();
                                String title = element.get("title").toString();
                                String imgURL = element.get("images").toString();
                                String info = element.get("id").toString();
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("title", title);
                                map.put("img", imgURL);
                                map.put("info", info);
                                list.add(map);
                            }

                        }
                        catch (Exception ex)
                        {
                        }

                    }
                });
        return list;
    }*/
}